

let mysqlModule = require("mysql");

let db = require("../config/db");

let application = require("../config/application");

class mysql {

    /**
     * 初始化
     */
    constructor() {

    }


    query(sql, value) {

        let promise = new Promise(function (resolve, reject) {
            let connection = mysqlModule.createConnection({ host: db.host, user: db.user, password: db.password, database: db.database });

            connection.connect();
            /**
             * 推荐使用占位符方式查询，占位符可以防止 sql注入 占了 80%漏洞都是sql
             */
            connection.query(sql, value, function (err, result) {

                if (err) {
                    console.log(sql);
                    console.log(value);
                    reject(err.message)
                } else {
                    if (application.even == "dev") {//开发环境也打印sql
                        console.log('执行的sql=====' + sql);
                        console.log('sql对应的值');
                        console.log(value);
                    }
                    //setTimeout(function () {//模拟数据的慢查询
                    resolve(result);
                    //},5000)

                }

                connection.end();
            })


        })
        return promise;

    }

    /**
     * 简单的数据查询
     * @param {}} condtion json 格式
     */
    async select(condition, limit) {
        let sql = "select * from " + this.table;
        let vals = [];
        if (condition) {
            sql += ' where ';
            console.log(condition);
            for (let element in condition) {
                sql += ' ' + element + '=? and';
                vals.push(condition[element]);
            };
            sql = sql.replace(new RegExp('\\' + 'and' + '+$', 'g'), '');
        }
        if (!limit) {
            limit = 20;
        }
        sql += ' limit ' + limit;
        return await this.query(sql, vals)
    }

    /**
     * 查询一条数据
     * @param  condtion 
     */
    async find(condition) {
        let result = await this.select(condition, 1);
        if (result.length == 0) {
            return {};
        }
        return result[0];
    }

     /**
     * 删除数据
     * @param  condtion 
     */
      async delete(condition) {
        if (!condition) {
            throw Error('写入数据为空！');
        };
        let sql="delete from "+this.table+' where ';
        let vals=[];
        for (let element in condition) {
            sql += ' ' + element + '=? and';
            vals.push(condition[element]);
        };
        sql = sql.replace(new RegExp('\\' + 'and' + '+$', 'g'), '');
        return await this.query(sql, vals);
    }



    /**
     * condition 为json 格式
    * 写入数据
    * @param  condtion 
    */
    async insert(condition) {
        if (!condition) {
            throw Error('写入数据为空！');
        };
        let sql = "insert into " + this.table + "(";
        let vals = 'values (';
        let valArr = [];
        for (let key in condition) {
            sql += key + ",";
            vals += '?,';
            valArr.push(condition[key]);
        }
        sql = sql.replace(new RegExp('\\' + ',' + '+$', 'g'), '');
        sql += ')'
        vals = vals.replace(new RegExp('\\' + ',' + '+$', 'g'), '');
        vals += ')';
        sql += vals
        let result = await this.query(sql, valArr);
        return result;
    }

    /**
     * 删除数据
     * @param  condtion 
     */
     async update(data,condition) {
        if (!condition) {
            throw Error('更新条件为空数据为空!');
        };
        if (!data) {
            throw Error('更新数据不能为空!');
        };
        let sql="update "+this.table+' set ';
        let valArr=[];
        for (let ele in data) {
            //sql += ' ' + element + '=? and';
            sql+=' ' + ele + '=? ,';
            valArr.push(data[ele]);
        };
        sql = sql.replace(new RegExp('\\' + ',' + '+$', 'g'), '');
        sql+=' where ';
        for (let element in condition) {
            //sql += ' ' + element + '=? and';
            sql+=' ' + element + '=? and';
            valArr.push(condition[element]);
        };
        sql = sql.replace(new RegExp('\\' + 'and' + '+$', 'g'), '');
        return await this.query(sql, valArr);
    }



}

module.exports = mysql;